package asynqmq

import (
	"context"
	"fmt"
	"strconv"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/hibiken/asynq"
)

func Init(ctx context.Context) {
	go run(ctx)
}

func run(ctx context.Context) {
	mux := Register()
	redisCfg := g.Cfg().MustGet(ctx, "redis.default").Map()
	addr := redisCfg["address"].(string)
	password := redisCfg["pass"].(string)
	dbStr := redisCfg["db"].(string)
	db, err := strconv.Atoi(dbStr)
	if err != nil {
		panic(err)
	}
	server := asynq.NewServer(
		asynq.RedisClientOpt{Addr: addr, Password: password, DB: db},
		asynq.Config{
			IsFailure: func(err error) bool {
				fmt.Printf("asynq server exec task >>>>>>>>>>>>>>>>>>>>>>  err : %+v \n", err)
				return true
			},
			Concurrency: 20,
		},
	)

	defer func() {
		server.Shutdown()
		if err := recover(); err != nil {
			g.Log().Error(ctx, "DoTask panic recovered:", err)
			go run(ctx) // 重新启动
		}
	}()

	err = server.Run(mux)

	if err != nil {
		panic(err)
	}
}
